<template>
	<view class="goodsView">
		<uni-forms
			ref="goodsForm"
			:model="goodsFormData"
			:label-width="100"
			label-align="right"
			:rules="goodsRules"
		>
			<uni-forms-item label="商品图片">
				<uni-file-picker
					v-model="goodsFormData.thumb"
					file-mediatype="image"
					mode="grid"
					:auto-upload="false"
					ref="photos"
				></uni-file-picker>
			</uni-forms-item>
			<uni-forms-item
				label="商品名称"
				name="name"
				required
			>
				<uni-easyinput
					v-model="goodsFormData.name"
					placeholder="请输入商品名称"
					trim="both"
				></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item
				label="产品分类"
				required
				name="category_id"
			>
				<uni-data-select
					collection="my-mall-categories"
					field="_id as value, name as text"
					v-model="goodsFormData.category_id"
					placeholder="请选择商品分类"
				></uni-data-select>
			</uni-forms-item>
			<uni-forms-item
				label="商品价格"
				name="price"
				required
			>
				<uni-easyinput
					type="number"
					trim="both"
					v-model="goodsFormData.price"
					placeholder="请输入商品价格"
				></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item label="商品原价">
				<uni-easyinput
					type="number"
					trim="both"
					v-model="goodsFormData.before_price"
					placeholder="请输入商品原价"
				></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item label="商品属性">
				<u-cell
					:title="skuTitle"
					isLink
					:border="false"
					@click="clickSelect"
				></u-cell>
				<view class="skuList">
					<view
						class="item"
						v-for="item in goodsFormData.sku_select"
					>
						<view class="left">{{ item.skuName }}:</view>
						<view class="right">{{ skuChildName(item.children) }}</view>
					</view>
				</view>
			</uni-forms-item>
			<uni-forms-item label="商品描述">
				<uni-easyinput
					type="textarea"
					placeholder="请输入商品描述信息"
					v-model="goodsFormData.description"
				></uni-easyinput>
			</uni-forms-item>
		</uni-forms>
		<view class="btnView">
			<button
				type="primary"
				@click="onSubmit"
			>
				确认提交
			</button>
		</view>

		<uni-popup
			ref="attrWrapPop"
			type="bottom"
		>
			<view class="attrWrapper">
				<view class="head">
					<view class="title">商品属性</view>
					<view
						class="addAttr"
						@click="clickAddAttr()"
					>
						+ 添加属性
					</view>
				</view>
				<view class="body">
					<view
						class="item"
						v-for="(item, index) in skuArr"
					>
						<view class="top">
							<checkbox
								:checked="item.checked"
								@click="changeCheckBox(index)"
							/>
							<view class="font">
								{{ item.skuName }}
							</view>
						</view>
						<view
							class="btnGroup"
							v-if="item.checked"
						>
							<view
								class="btn"
								:class="child.checked ? 'active' : ''"
								v-for="(child, cindex) in item.children"
								@click="clickChildBtn(index, cindex)"
							>
								{{ child.name }}
							</view>
							<view
								class="btn"
								@click="clickAddAttr(index)"
							>
								<u-icon name="plus"></u-icon>
							</view>
						</view>
					</view>
				</view>
				<view class="foot">
					<button
						type="primary"
						@click="clickConfirmSelect"
					>
						确认选择
					</button>
				</view>
			</view>

			<!-- <view class="safe-area-bottom"></view> -->
		</uni-popup>

		<uni-popup ref="addAttrPop">
			<uni-popup-dialog
				mode="input"
				title="新增"
				placeholder="请输入新增内容"
				@confirm="dialogConfirm"
			></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
// 引入sku云对象，并开启自定义ui
const skuCouldObj = uniCloud.importObject('my-mall-sku', {
	customUI: true
});

const goodsCouldObj = uniCloud.importObject('my-mall-goods', {
	customUI: true
});

let goodId;
export default {
	data() {
		return {
			goodsFormData: {
				name: '',
				thumb: [],
				category_id: null,
				price: null,
				before_price: null,
				sku_select: []
			},
			addAttrType: 'parent', // parent-父类，child-子类
			goodsRules: {
				name: {
					rules: [
						{
							required: true,
							errorMessage: '请输入商品名称'
						}
					]
				},
				price: {
					rules: [
						{
							required: true,
							errorMessage: '请输入原价'
						}
					]
				},
				category_id: {
					rules: [
						{
							required: true,
							errorMessage: '请选择分类'
						}
					]
				}
			},
			skuArr: []
		};
	},
	onLoad(e) {
		this.isManage();
		goodId = e?.id ?? null;
		if (goodId) this.getGoodsOne();
		this.getSkuData();
	},
	methods: {
		// 获取一个商品
		async getGoodsOne() {
			console.log(goodId);
			let res = await goodsCouldObj.getOne(goodId);
			this.goodsFormData = res.data[0];
		},
		skuChildName(arr) {
			let newArr = arr.map((item) => {
				return item.name;
			});

			return newArr.join('/');
		},
		clickConfirmSelect() {
			let filterArr = this.skuArr
				.filter((parentValue) => {
					// 子元素中，是否有选
					let state = parentValue.children.some((child) => child.checked);
					return parentValue.checked && state;
				})
				.map((parentValue) => {
					let children = parentValue.children.filter((childValue) => {
						return childValue.checked;
					});
					return {
						...parentValue,
						children
					};
				});
			this.goodsFormData.sku_select = filterArr;

			this.$refs.attrWrapPop.close();
		},
		async getSkuData() {
			let res = await skuCouldObj.get();
			this.skuArr = res.data;
			// console.log(res);
		},
		// 添加属性弹窗确认按钮
		async dialogConfirm(e) {
			if (!e) return;
			if (this.addAttrType == 'parent') {
				let obj = {
					skuName: e,
					checked: true,
					children: []
				};
				let res = await skuCouldObj.add(obj);
				obj._id = res.id;
				// 前端显示
				this.skuArr.push(obj);
			} else if (this.addAttrType == 'child') {
				let obj = {
					name: e,
					checked: true
				};
				let id = this.skuArr[this.attrIndex]._id;
				let res = await skuCouldObj.updateChild(id, obj);
				// 前端显示
				this.skuArr[this.attrIndex].children.push(obj);
			}
		},
		// 点击添加按钮
		clickAddAttr(index) {
			if (index == null) {
				this.addAttrType = 'parent';
				this.attrIndex = null;
			} else {
				this.addAttrType = 'child';
				this.attrIndex = index;
			}
			this.$refs.addAttrPop.open();
		},
		// 勾选父选框
		changeCheckBox(index) {
			this.skuArr[index].checked = !this.skuArr[index].checked;
		},
		// 勾选子选框
		clickChildBtn(index, cindex) {
			this.skuArr[index].children[cindex].checked = !this.skuArr[index].children[cindex].checked;
		},
		// 点击商品属性
		clickSelect() {
			this.$refs.attrWrapPop.open();
			this.arrSetCheck(this.skuArr, this.goodsFormData.sku_select, '_id');
		},
		// 比较两个数组，勾选选中项
		arrSetCheck(arr1, arr2, key) {
			arr1.forEach((item) => {
				arr2.forEach((row) => {
					if (item[key] == row[key]) {
						item.checked = true;
						if (item?.children?.length) this.arrSetCheck(item.children, row.children, 'name');
					}
				});
			});
		},
		// 点击提交表单
		onSubmit() {
			this.$refs.goodsForm
				.validate()
				.then(async (res) => {
					let res2 = await this.$refs.photos.upload();
					if (res2.length) {
						this.toDataBase(this.goodsFormData);
					} else {
						throw '图片上传失败';
					}
				})
				.catch((err) => {
					console.log(err);
				});
		},
		// 上传到云数据库
		async toDataBase() {
			this.goodsFormData.thumb = this.goodsFormData.thumb.map((item) => {
				return {
					url: item.url,
					name: item.name,
					extname: item.extname
				};
			});
			let toastTitle;
			if (goodId) {
				toastTitle = '修改成功';
				let res = await goodsCouldObj.update(this.goodsFormData);
				console.log(res);
			} else {
				toastTitle = '新增成功';
				let res = await goodsCouldObj.add(this.goodsFormData);
			}

			uni.showToast({
				title: toastTitle
			});

			setTimeout(() => {
				uni.navigateBack();
			}, 1500);
		}
	},
	computed: {
		skuTitle() {
			if (this.goodsFormData.sku_select.length) {
				let arr = this.goodsFormData.sku_select.map((item) => {
					return item.skuName;
				});
				return arr.join('/');
			}
			return '添加属性';
		}
	}
};
</script>

<style lang="scss" scoped>
.goodsView {
	padding: 30rpx;
	.skuList {
		.item {
			padding: 30rpx;
			background-color: $page-bg-color;
			margin: 15rpx 0;
			@include flex-box-set(start);
		}
	}
}

::v-deep .uni-file-picker__container {
	display: flex;

	flex-wrap: nowrap;
	overflow-x: scroll;
	.file-picker__box {
		flex-basis: 88px;
		flex-shrink: 0;
		white-space: nowrap;
	}
}

.attrWrapper {
	padding: 30rpx;
	background-color: #fff;
	border-radius: 20rpx 20rpx 0 0;
	.head {
		@include flex-box();
		font-size: 34rpx;
		margin-bottom: 30rpx;
		.title {
			font-weight: bold;
		}
		.addAttr {
			color: $brand-theme-color-aux;
		}
	}
	.body {
		.item {
			border-top: 1px solid $border-color-light;
			&:last-child {
				border-bottom: 1px solid $border-color-light;
			}
			.top {
				padding: 30rpx 0;
				@include flex-box-set(start);
				.font {
					padding-left: 10rpx;
					font-weight: bold;
				}
			}
			.btnGroup {
				padding: 10rpx 0 30rpx;
				@include flex-box-set(start);
				flex-wrap: wrap;

				.btn {
					padding: 0rpx 25rpx;
					height: 60rpx;
					border: 1rpx solid $border-color-light;
					margin-right: 20rpx;
					border-radius: 10rpx;
					color: $text-font-color-2;
					margin-bottom: 20rpx;
					@include flex-box-set();
					&.active {
						border-color: $brand-theme-color;
						color: $brand-theme-color;
						background: rgba(236, 87, 79, 0.1);
					}
				}
			}
		}
	}
	.foot {
		padding: 50rpx 200rpx;
	}
}
</style>
